//index.js
const app = getApp()
const api = require('../../api/api.js')
let pagenum = 0
let watcher = ''
const db = wx.cloud.database()
const _ = db.command
Page({
  data: {
    TabCur:0,
    list:[],
    state:false,
    cardCur: 0,
    tablist: [],
    swiperList: [],
    searchval:'',
    showLogin:false,
    DotStyle:true,
    nodata:false,
    show:false,
    container:null
  },
  DotStyle(e) {
    this.setData({
      DotStyle: e.detail.value
    })
  },
  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },

  imgwraptap(e){
    let _id = e.currentTarget.dataset._id
    wx.navigateTo({
      url: '../details/details?id=' + _id,
    })
  },


  /**
   * 关闭授权
   */
  navigateBack(){
    this.setData({
      showLogin: !this.data.showLogin
    });
  },
  /**
   * 搜索文本值
   */
  searchtap(e){
    this.setData({
      searchval: e.detail.value,
    })
  },
  /**
   * 搜索
   */
  async search(){

    let data = await api.search(this.data.searchval)
    this.setData({
      list:data.data
    })
    if (data.data.length == 0) {
      this.setData({
        nodata: true
      })
    }
    console.log(data.data)
  },
  /**
   * tab切换
   */
  async tabSelect(e) {
    this.setData({
      show:false,
      nodata:false,
      NoPulling:false
    })
    let type = e.target.dataset.type
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
    console.log(e)
    let data = await api.getdata(0, type )
    this.setData({
      list: data.data,
      show:true
    })
    if (data.data.length == 0) {
      this.setData({
        nodata: true
      })
    }
    if (data.data.length < 10) {
      this.setData({
        NoPulling: true
      })

    }
  },
  onLoad: async function(obs) {
    let that = this
  //  let swiperdat = await api.getswiper()
   let tablist = await api.gettab()
   let notice = await api.getnotice()
   let data = await api.getdata()

    console.log(tablist)
    if (data.data.length == 0) {
      this.setData({
        nodata: true
      })
      
    }
    console.log(notice)

    let data1 = wx.createIntersectionObserver().observe('.listwrap ',res=>{
      console.log(res)
    })
  console.log('data',data1)
   this.setData({
     list: data.data,
     state:true,
    //  swiperList: swiperdat.data,
     tablist: tablist.data,
     show:true,
     notice:notice.data[0]
   })
    wx.stopPullDownRefresh()
   if (data.data.length<10){
     this.setData({
       NoPulling : true
     })
   }
   // 在页面中定义插屏广告
let interstitialAd = null

// 在页面onLoad回调事件中创建插屏广告实例

if (wx.createInterstitialAd) {
  interstitialAd = wx.createInterstitialAd({
    adUnitId: 'adunit-317d345bdd80af32'
  })
  interstitialAd.onLoad(() => {})
  interstitialAd.onError((err) => {})
  interstitialAd.onClose(() => {})
}

// 在适合的场景显示插屏广告
if (interstitialAd) {
  interstitialAd.show().catch((err) => {
    console.error(err)
        // 失败重试
        interstitialAd.load()
        .then(() => videoAd.show())
        .catch(err => {
          console.log('激励视频 广告显示失败')
        })
  })
}



watcher = db.collection('notice')
 .where({
   text: _.exists(true)
 })
 .watch({
   onChange: function(snapshot) {
     console.log('docs\'s changed events', snapshot.docChanges[0].doc)
     that.setData({
      notice:snapshot.docChanges[0].doc
     })
     console.log('query result snapshot after the event', snapshot.docs)
     console.log('is init data', snapshot.type === 'init')
   },
   onError: function(err) {
     console.error('the watch closed because of error', err)
   }
 })

  },
  /**
   * 轮播图查看图片
   */
  previewImage(e){
    let url = e.currentTarget.dataset.url
    let urls = []
    this.data.swiperList.map(item=>{
      urls.push(item.url) 
    })
    console.log(url, urls)
    wx.downloadFile({
      url: 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/105/105-bigskin-1.jpg', //仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log(res)
        if (res.statusCode === 200) {

        }
      }
    })
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  /**
   * 下拉
   */
  async onPullDownRefresh  (){
    this.setData({
      TabCur:0
    })
  this.onLoad()

  },
  /**
   * 分享
   */
  onShareAppMessage() {
    return {
      title: this.data.list[0].chinmsg,
      path: '/pages/index/index',
      imageUrl:this.data.list[0].imgurl
    }
  },
// onReady(){
//   wx.showShareMenu({
//     withShareTicket: true,
//     menus: ['shareAppMessage', 'shareTimeline']
//   })
// },
onShareTimeline(){
  return {
    title: this.data.list[0].chinmsg,
    query: {test:1,type:1},
    imageUrl:this.data.list[0].imgurl
  }
},
onUnload(){
  watcher.close()
},

  /**
   * 上拉加载
   */
  async onReachBottom(){
   if (this.data.NoPulling){
     return
   }
    pagenum = ++pagenum
    console.log(pagenum)
    let data = await api.getdata(pagenum)
    console.log(data)
    if (data.data.length){
      this.setData({
        list: [...this.data.list,...data.data]
      })
    }

    if (data.data.length < 10) {
      console.log('NoPullingtrue')
      this.setData({
        NoPulling: true
      })
    }
  },
    // // 获取滚动条当前位置
    onPageScroll: function (e) {
      if (e.scrollTop > 1800) {
        this.setData({
          floorstatus: true
        });
      } else {
        this.setData({
          floorstatus: false
        });
      }
    },
    //回到顶部
    goTop: function (e) {  // 一键回到顶部
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
      }
    }
  
})
